package com.cdivtc.management.service;


import com.cdivtc.management.dao.*;
import com.cdivtc.management.pojo.*;
import com.cdivtc.management.pojo.vo.Studentbatchvo;
import com.cdivtc.management.utils.ExcelUtils;
import com.cdivtc.management.utils.FastDFSClient;
import com.cdivtc.management.utils.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service

public class UserSerive {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private FastDFSClient dfsClient;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RoleMapper roleMapper;

    public User findByUsername(String username) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        User user = userMapper.selectOneByExample(example);

        return user;
    }

    public void addstudentbeach(MultipartFile studentfile) throws IOException {
        Date date = new Date();
        Map map = excelUtils.readExcelByStudent(studentfile.getInputStream(), Studentbatchvo.class, "student");
        List<User> userlist = (List<User>) map.get("user");
        List<UserRole> userRoles = (List<UserRole>) map.get("userRoleKeys");

        List<Studentbatchvo> Studentbatchvotlist = (List<Studentbatchvo>) map.get("student_teacher");
        List<Student> students = new ArrayList<>();
        for (Studentbatchvo s : Studentbatchvotlist
        ) {
            Student student = new Student();
            BeanUtils.copyProperties(s, student);
            int insert = studentMapper.insert(student);
        }
//        插入数据
        for (User user : userlist) {
            int insert = userMapper.insert(user);
        }
        for (UserRole userRole : userRoles) {
            int insert = userRoleMapper.insert(userRole);
            if (insert <= 0) {
                throw new IllegalArgumentException("添加失败");
            }
        }



        System.out.println("(new Date().getTime()-date.getTime()) = " + (new Date().getTime() - date.getTime()));



    }

    public void addstudentone(Student student) {
        User byUsername = findByUsername(student.getStudentId());
        if (byUsername != null) {
            throw new IllegalArgumentException("用户已存在");
        }

        student.setId(String.valueOf(idWorker.nextId()));
        student.setState("1");
        User user = new User();
        user.setPassword(student.getStudentId());
        user.setUsername(student.getStudentId());
        String uid = String.valueOf(idWorker.nextId());
        user.setUid(uid);
        user.setState("1");
        student.setUId(uid);
//        插入数据
        userMapper.insert(user);
        studentMapper.insert(student);
        addRole(uid, "student");
    }

    //添加老师
    public void addteacherone(Teacher teacher) {
//        查询是否存在用户信息

        User byUsername = findByUsername(teacher.getJobNumber());
        if (byUsername != null)
            throw new IllegalArgumentException("用户已存在");
        User user = new User();
        user.setUsername(teacher.getJobNumber());
        user.setPassword(teacher.getJobNumber());
        teacher.setId(String.valueOf(idWorker.nextId()));
        String uid = String.valueOf(idWorker.nextId());
        user.setUid(uid);
        teacher.setUId(uid);
        userMapper.insert(user);
        teacherMapper.insert(teacher);
        addRole(uid, "teacher");
    }

    //    添加用户权限
    public void addRole(String uid, String role) {
        UserRole userRoleKey = new UserRole();
        userRoleKey.setUid(uid);

        Role role1 = new Role();
        role1.setRname(role);
        Role role2 = roleMapper.selectOne(role1);
        userRoleKey.setRid(role2.getRid());
        userRoleMapper.insert(userRoleKey);
    }

    //批量添加老师
    public void addteacherbeach(MultipartFile teacher) throws IOException {
        Map map = excelUtils.readExcelByStudent(teacher.getInputStream(), Teacher.class, "teacher");
        List<User> users = (List<User>) map.get("user");
        List<Teacher> student_teacher = (List<Teacher>) map.get("student_teacher");
        List<UserRole> userRoleKeys = (List<UserRole>) map.get("userRoleKeys");

        for (Teacher s : student_teacher
        ) {
            Teacher student = new Teacher();
            BeanUtils.copyProperties(s, student);
            int insert = teacherMapper.insert(student);
        }
//        插入数据
        for (User user : users) {
            int insert = userMapper.insert(user);
        }
        for (UserRole userRole : userRoleKeys) {
            int insert = userRoleMapper.insert(userRole);
            if (insert <= 0) {
                throw new IllegalArgumentException("添加失败");
            }
        }




    }

    //    添加管理员
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public void addadmin(User user) {
//        查询用户是否已经存在
        User byUsername = findByUsername(user.getUsername());
        if (byUsername != null)
            throw new IllegalArgumentException("用户已存在");
        user.setUid(idWorker.nextId() + "");
        userMapper.insert(user);
//添加权限
        addRole(user.getUid(), "admin");


    }

//    查询权限

    public User selectRole(User user) {

        UserRole userRoles = new UserRole();
        userRoles.setUid(user.getUid());
//        通过用户角色表查询出角色id
        List<UserRole> select = userRoleMapper.select(userRoles);

        List<Role> roleSet = new ArrayList<>();
        for (UserRole r : select) {
            Example example = new Example(Role.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("rid", r.getRid());

            Role role1 = roleMapper.selectOneByExample(example);
            System.out.println("role1 = " + role1 + "***************" + r);
            roleSet.add(role1);
        }
        System.out.println("select = " + select + "userRoles" + userRoles);
        user.setRoles(roleSet);
        return user;
    }

    //根据用户id 查学生
    public Student stuQueryByUid(String uid) {
        Student student = new Student();
        student.setUId(uid);
        student = studentMapper.selectOne(student);
        if (student == null)
            throw new IllegalArgumentException("学生不存在");
        return student;
    }

    //根据用户id 查老师
    public Teacher teaQueryByUid(String uid) {
        Teacher student = new Teacher();
        student.setUId(uid);
        student = teacherMapper.selectOne(student);
        if (student == null)
            throw new IllegalArgumentException("学生不存在");
        return student;
    }

    //根据用户名id查找用户、
    public User findByUid(String username) {
        User user = userMapper.selectByPrimaryKey(username);
        return user;
    }

    //查询旧密码
    public User findBypwd(User user) {

        user = userMapper.selectOne(user);
        return user;
    }

    //    修改用户密码
    public User updateUpdatePwd(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0) {
            throw new IllegalArgumentException("修改失败");
        }
        return user;
    }

    //修改学生信息
    public void updateStuInfo(Student student) {

        int i = studentMapper.updateByPrimaryKeySelective(student);
        if (i == 0)
            throw new IllegalArgumentException("修改失败");

    }

    //修改老师信息
    public void updateTeaInfo(Teacher teacher) {

        int i = teacherMapper.updateByPrimaryKeySelective(teacher);
        if (i == 0)
            throw new IllegalArgumentException("修改失败");

    }

    public <T> void updateImage(String imageurl, String Uid, Class<T> clazz, Integer role) {

        Example example = new Example(clazz);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uId", Uid);
        int count = 0;
        if (role < 2000) {
            Student student = new Student();
            student.setFaceIcon(imageurl);
            System.out.println("student = " + student);
            count = studentMapper.updateByExampleSelective(student, example);
        } else {
            Teacher teacher = new Teacher();
            teacher.setFaceIcon(imageurl);
            System.out.println("teacher = " + teacher);
            count = teacherMapper.updateByExampleSelective(teacher, example);
        }
        if (count == 0)
            throw new IllegalArgumentException("修改头像失败");
    }

    //修改权限
    public void modifyRole(String uid,Role rid) {
//        根据用户名和角色id进行修改




    }

    //    查询所有角色列表
    public List<Role> queryAllRole() {

        List<Role> roleList = roleMapper.selectAll();
        return roleList;
    }

    public void updateRole(UserRole role) {
        userRoleMapper.updateByPrimaryKey(role);

    }

    public List<Teacher> queryByAllteacher() {

        List<Teacher> teacherList = teacherMapper.selectAll();
        return teacherList;
    }

    public List<Student> queryByStuClazz(String clazz) {

        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("clazzId", clazz);

        List<Student> students = studentMapper.selectByExample(example);
        return students;
    }


    public void reset_password(String uid) {
        User user = new User();
        user.setUid(uid);
        user.setPassword("123456");
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0)
            throw new IllegalArgumentException("重置密码失败");
    }

    public void deleteUser(String uid) {
        userMapper.deleteByPrimaryKey(uid);
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uId", uid);
        studentMapper.deleteByExample(example);


    }
}
